//
//  BmPopupBaseView.m
//  BimaMatrix
//
//  Created by Aimeow on 4/28/15.
//  Copyright (c) 2015 Aimeow. All rights reserved.
//

#import "BmPopupBaseView.h"

@interface BmPopupBaseView()

@property (nonatomic , strong) UIImageView *maskView;
@property (nonatomic , strong) UIWindow *window;
@property (nonatomic , strong) UITapGestureRecognizer *backgroundDismissGesture;

@end

@implementation BmPopupBaseView
@synthesize window;
- (instancetype)init
{
    self = [super init];
    if (self) {
        id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
        if ([delegate respondsToSelector:@selector(window)])
            window = [delegate performSelector:@selector(window)];
        else
            window = [[UIApplication sharedApplication] keyWindow];
        
        self.backgroundDismissGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapOnMaskView:)];
        _contentView = [[BmView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
        _contentView.backgroundColor = [UIColor whiteColor];
    }
    
    return self;
}

- (UIImageView *)maskView
{
    if (_maskView == nil) {
        _maskView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        _maskView.backgroundColor = [UIColor colorwithHexString:@"#000000" alpha:0.4];
        _maskView.alpha = 0;
        _maskView.userInteractionEnabled = YES;
        [_maskView addGestureRecognizer:self.backgroundDismissGesture];
        
    }
    return _maskView;
}

- (void)show
{
    [window addSubview:self.maskView];
    [window addSubview:self.contentView];
    
    self.contentView.top = window.bottom;
    
    NSUInteger options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut;
    
    [UIView animateWithDuration:0.15 delay:0 options:options animations:^{
        self.maskView.alpha = 1;
        self.contentView.alpha = 1;
        self.contentView.bottom = window.bottom;

    }completion:^(BOOL finished){ }];
}

- (void)dismiss
{
    NSUInteger options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseIn;
    
    [UIView animateWithDuration:0.15 delay:0 options:options animations:^{
        self.contentView.top = window.bottom;
        self.maskView.alpha = 0;
    }completion:^(BOOL finished)
     {
         [self.contentView removeFromSuperview];
         [self.maskView removeFromSuperview];
         //         self.contentView = nil;
         //         self.maskView = nil;
     }];
}

- (void)didTapOnMaskView:(id)sender
{
    [self dismiss];
}

@end